import time

class OrderItemClass:  
    def __init__(self):  
        self.Type = None  # Item type  
        self.Item = None  # Item name 
        self.Quality = None  # Item quality level
        self.Material = None # Material of the item
        self.CompletedAmount = 0  # Completed quantity of the item  
        self.Amount = 0  # Total ordered quantity of the item
        self.PreviousPage = False # Previous page existence
        self.NextPage = False # Next page existence
        self.DropAction = None # Action to perform on item drop

def GetBagMatrix():  
    """  
    Obtain and return a matrix of items grouped by their Z-axis position.  
    """  
    # Set up an item filter to select specific items on the ground   
    filter = Items.Filter()  
    filter.Enabled = True  
    filter.OnGround = True  
    filter.Graphics.Add(0x0E76)  
      
    # Get a list of items that meet the criteria  
    bags = Items.ApplyFilter(filter)  
    print(f"Found {len(bags)} bags.")  
      
    # Group items based on their Z-axis position  
    groupedItems = {}  
    for bag in bags:  
        z_value = bag.Position.Z  
        groupedItems.setdefault(z_value, []).append(bag)  
      
    # Sort and construct the item matrix  
    bagMatrix = [group for _, group in sorted(groupedItems.items())]  
      
    # Return the constructed item matrix  
    return bagMatrix
  
def FindPendingOrderBookInFirstRow(bagMatrix):  
    """    
    Search for a pending order book in the first row of the bag.    
    """    
  
    OrderBookItemID = 0x2259  # The item ID for the order book  
    orderBook = None          # Initialize the order book variable    
  
    for element in bagMatrix[0]:    
        # Attempt to use the item and search for the order book  
        Items.UseItem(element.Serial)  
        Items.Message(element, 33, "!")  
        time.sleep(0.8)  
  
        # Search for the order book based on the item ID  
        orderBook = Items.FindByID(OrderBookItemID, -1, element.Serial)  
        if orderBook is not None:  
            Items.Message(element, 33, "!!!")  
            Items.Message(element, 33, "!!!")  
            Items.Message(element, 33, "!!!")  
            return orderBook  # Return the found order book object    
               
        time.sleep(0.2)  
    return orderBook  # Return None if the order book is not found in the first row

def FetchPendingOrderBookFrom(orderBook):  
    # Move the order book to the player's backpack  
    Items.Move(orderBook.Serial, Player.Backpack.Serial, 1)  
    time.sleep(1)  # Wait for one second

def ParseOrderBookGumpList(gumpStringList):  
    # 单独定义一个列表来存储需要忽略的标题  
    IgnoreList = [  
    "Bulk Order Book", "Type", "Item", "Quality", "Material", "Amount",  
    "Set Filter", "Using Book Filter", "EXIT", "Drop", "Price", "Set",  
    "Next page",  
    ]  

    # 初始化变量  
    OrderList = []  
    CurrentOrder = None  
    index = 0  
    
    # 解析字符串列表  
    for line in gumpStringList:  
        # 跳过空行和标题行  
        if not line or line in IgnoreList:  
            continue  
            
        # 检查是否为新的订单类型  
        if line in ['Small', 'Large']:  
            CurrentOrder = OrderItemClass()  
            CurrentOrder.Type = line
            OrderList.append(CurrentOrder)    
        elif CurrentOrder:  
            if not CurrentOrder.Item:  
                CurrentOrder.Item = line  
            elif not CurrentOrder.Quality:  
                CurrentOrder.Quality = line  
            elif not CurrentOrder.Material:  
                CurrentOrder.Material = line  
            # 检查是否为数量信息  
            elif ' / ' in line:  
                completed, total = line.split(' / ')  
                OrderList[index].CompletedAmount = int(completed)  
                OrderList[index].Amount = int(total)  
                index += 1  

    if OrderList:  # 确保OrderList不为空  
        start_value = 5  # 初始值为5  
        for i, order in enumerate(OrderList):  
            order.DropAction = start_value + i * 2  # 每个订单的DropAction以2递增
    return OrderList  

BagMatrix = None  
OrderBook = None

if BagMatrix is None:
    BagMatrix = GetBagMatrix()

OrderBook = FindPendingOrderBookInFirstRow(BagMatrix)
if OrderBook is None:
    print("ob=none")
print(OrderBook.Serial)
FetchPendingOrderBookFrom(OrderBook)

Items.UseItem(OrderBook.Serial)
Gumps.WaitForGump(1425364447, 10000)
GumpStringList = Gumps.LastGumpGetLineList()

OrderList = ParseOrderBookGumpList(GumpStringList) 

if len(OrderList):
    # 打印解析后的订单列表  
    for order in OrderList:  
        print(f"Type: {order.Type}")  
        print(f"Item: {order.Item}")  
        print(f"Quality: {order.Quality}")  
        print(f"Material: {order.Material}")  
        print(f"CompletedAmount: {order.CompletedAmount}")  
        print(f"Amount: {order.Amount}")  
        print(f"DropAction: {order.DropAction}")  # 打印DropAction属性  
        print("---")  # 分隔符，以便更清晰地查看每个订单的信息

# 遍历OrderList，执行未完成的订单  
for order in OrderList:  
    if order.CompletedAmount < order.Amount:  
        # 如果CompletedAmount小于Amount，则执行DropAction  
        if order.DropAction is not None:  
            Gumps.SendAction(1425364447, order.DropAction)
        else:  
            print("DropAction is not set for this order.")

#num = Items.GetPropValue(orderBook, "Deeds in book")
#print(num)
#num = Items.GetPropValue(orderBook, "Weight")
#print(num)
#aa = Items.GetPropValueString(orderBook, "Book Name")
#print(aa)

# 遍历并打印矩阵中的物品位置信息  
#for layer in BagMatrix:  
#    for item in layer:  
 #       Items.Message(item, 88, f"{item.Position.X}")  
 #       Items.Message(item, 88, f"{item.Position.Y}")  
 #       Items.Message(item, 88, f"{item.Position.Z}")  
 #       time.sleep(0.5)  

 
#Items.UseItem(0x43562899)
#Gumps.WaitForGump(1425364447, 10000)
#Gumps.SendAction(1425364447, 3) #Next page
#Gumps.WaitForGump(1425364447, 10000)
#Gumps.SendAction(1425364447, 2) # Previous page
#Gumps.WaitForGump(1425364447, 10000)
#Gumps.SendAction(1425364447, 0) #Exit
#Items.UseItem(0x43562899)